# -*- coding: utf-8 -*-
# author:WS
# time:2022/1/4:15:30:10
# ___msg___ = '查询专利法律状态'

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from quote_folder.Db_connect import DB_connect
from selenium.webdriver.common.by import By
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import random
import re
from 查询并更新系统专利状态 import is_search_ok


class patent_Status():
    def __init__(self, ):
        self.get_url = "http://cpquery.cnipa.gov.cn/"
        self.develop_con = DB_connect().online_db()  # 开发数据库连接
        self.develop_cur = self.develop_con.cursor()
        self.bigdata_con = DB_connect().online_big_data()  # 数据组数据库连接
        self.bigdata_cur = self.bigdata_con.cursor()
        self.redis_con = DB_connect().patents_reids()  # redis连接
        # self.applicant = applicant

    def login_gov(self, ):
        """ 登录中国及多国 """
        profile = webdriver.FirefoxOptions()
        profile.set_preference('network.proxy.type', 1)
        browser = webdriver.Firefox(options=profile, executable_path=r'D:\工具\geckodriver-v0.15.0-win64\geckodriver.exe')
        browser.get(self.get_url)
        time.sleep(5)
        WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "username1"))).clear()
        browser.find_element_by_id('username1').send_keys('18240721210')
        browser.find_element_by_id('password1').clear()
        browser.find_element_by_id('password1').send_keys('Zx123456~')
        time.sleep(5)
        is_search_ok(browser)
        current_url = browser.current_url
        return browser, current_url

    # 2020207090033
    username_info_list = [
        {"username": "15027399434", "password": "YJyj!1234"},
        {"username": "18071440149", "password": "Xhhg123456!"},
        {"username": "15978554102", "password": "Hhr31415926!"},
        {"username": "17362997328", "password": "Ccy1994!"},
        {"username": "13283766953", "password": "Ws1234567890~"},
        {"username": "13296529358", "password": "king123!B"},
        {"username": "18672982996", "password": "Ws1296817327~"},
        {"username": "17634417772", "password": "Ws123456cyh~"},
        {"username": "15039703722", "password": "WSws123456~"},
        {"username": "17710225394", "password": "Wq123456~"},
        {"username": "15318998458", "password": "123456Ws~"},
        {"username": '15938630689', 'password': "Whr123456~"},
        {"username": '18733151070', 'password': "Jx123456~"},
        {"username": '13995565120', 'password': "QWEqwe123~"},
        {"username": '15609508281', 'password': "Zq418317382@"},
        {"username": '15039738897', 'password': "Bl123456~"},
        {"username": '18240721210', 'password': "Zx123456~"},
        {"username": '15571590720', 'password': "Xj152588*"},
        {"username": '17630617464', 'password': "Zys123456~"},
        {"username": '17754433386', 'password': "Fj123456~"},
    ]

    def execute_sql(self, insert_sql):
        """
         执行sql插入
        :param insert_sql:
        :return:
        """
        try:
            self.bigdata_cur.execute(insert_sql)
        except Exception as E:
            print(insert_sql)
            print("插入错误：", E)

    def get_law(self, soup, sqh):
        """
        获取法律状态
        :param soup:
        :param sqh:
        :return:
        """
        update_time = time.strftime("%Y-%m-%d %H:%M:%S")
        law_status = soup.select('span[name="record_zlx:anjianywzt"]')
        Legal_Status = law_status[0]['title'].strip()
        print(Legal_Status)
        # self.update_mysql(sqh, Legal_Status, update_time)    # 执行sql语句

    def get_powerday(self, ):
        """
        授权日
        :return:
        """

    def get_powerday_html(self, sqh, browser, url):
        """
        抓取授权日html信息
        :return:
        """

    def get_html(self, sqh, browser, current_url):
        """
        获取专利信息html,抓取案件状态
        :param sqh:
        :param browser:
        :param current_url:
        :return:
        """
        sqh = re.sub(r'ZL', '', sqh)
        pat = ''.join(re.findall(r'select-key:shenqingh=(.*?)&select-key:backPage', current_url))
        url = re.sub(pat, sqh, current_url)
        browser.get(url)
        count_page = browser.page_source
        soup = BeautifulSoup(count_page, "lxml")
        self.get_law(soup, sqh)

    def update_mysql(self, sqh, status, now_time):
        """
        将法律状态插入数据库更新字段
        :param sqh:
        :param status:
        :return:
        """
        shen = 'CN' + sqh.strip()[:-1] + '.' + sqh.strip()[-1]
        # update_sql = f"""update patent_table set case_status='{status}' where application_number='{shen}'"""              # 以申请号来获取法律状态
        update_sql = f'''insert into External_orders(application_num, legal_status, update_time) values ('{shen}', '{status}', '{now_time}')'''
        self.bigdata_con.commit()
        self.execute_sql(update_sql)

    def run(self):
        """入口函数"""
        browser, current_url = self.login_gov()
        with open("sqh.txt", "r") as fw:
            ss = 0
            for application_number in fw:
                if ss >= 999:
                    break
                # print(f"开始抓取 {application_number}")
                ss += 1
                self.get_html(application_number, browser, current_url)
                # self.get_powerday_html(application_number, browser, )  # 授权日
        self.bigdata_con.commit()
        self.bigdata_cur.close()
        self.bigdata_con.close()
        self.develop_cur.close()
        self.develop_con.close()
        browser.close()


if __name__ == '__main__':
    func = patent_Status()
    func.run()  # 2020207090033
